<template>
    <div class="pagebody">
        <div class="crumbs">
            <el-breadcrumb separator="/">
                <el-breadcrumb-item> <i class="el-icon-lx-cascades"></i> 快递用户渠道管理 </el-breadcrumb-item>
            </el-breadcrumb>
        </div>
        <div class="container">
            <div class="search-box">
                <el-form :inline="true">
                    <el-form-item label="渠道名称">
                        <el-input v-model="searchSet.name" prefix-icon="el-icon-search" clearable placeholder="请输入渠道名称"></el-input>
                    </el-form-item>
                    <el-button type="primary" icon="el-icon-search" @click="handleSearch">搜索</el-button>
                    <el-button type="primary" icon="el-icon-plus" @click="handleAddNew">新建</el-button>
                </el-form>
            </div>
            <el-table :data="tableData" v-loading="tableLoading" border class="table" ref="mainTable" header-cell-class-name="table-header">
                <!-- <el-table-column prop="id" label="渠道ID" align="center"></el-table-column> -->
                <el-table-column prop="name" label="渠道名称" align="center"></el-table-column>
                <el-table-column prop="unitprice" label="单价" align="center"></el-table-column>
                <!-- <el-table-column prop="details" :formatter="DetailFormatter" label="项目信息" align="center"></el-table-column> -->
                <!-- <el-table-column type="expand">
                    <template slot-scope="props">
                        <el-table :data="props.row.details" stripe>
                            <el-table-column type="index" align="center" width="90"> </el-table-column>
                            <el-table-column prop="nationName" label="国家" align="center"></el-table-column>
                            <el-table-column prop="agentName" label="代理商" align="center"></el-table-column>
                        </el-table>
                    </template>
                </el-table-column> -->
                <el-table-column label="操作" width="340" align="center">
                    <template slot-scope="scope">
                        <el-button type="text" icon="el-icon-edit" @click="handleEdit(scope.$index, scope.row)">直乘价格</el-button>
                        <el-button type="text" icon="el-icon-s-ticket" @click="handlePrice(scope.$index, scope.row)">阶梯价格</el-button>
                        <el-button type="text" icon="el-icon-s-order" @click="handleDes(scope.$index, scope.row)">渠道描述</el-button>
                        <el-button type="text" icon="el-icon-delete" class="color-red" @click="handleDelete(scope.$index, scope.row)"
                            >删除</el-button
                        >
                    </template>
                </el-table-column>
            </el-table>
        </div>

        <el-dialog :title="editIsNewAdd ? '新建渠道' : '编辑渠道'" v-dialogDrag center :visible.sync="editVisible" width="60%">
            <el-form ref="form" :model="form" :rules="formRules" label-width="120px">
                <el-form-item label="渠道名称" prop="name">
                    <el-input
                        v-model="form.name"
                        placeholder="请输入名称"
                        maxlength="20"
                        show-word-limit
                        clearable
                        class="formInput"
                    ></el-input>
                </el-form-item>
                <el-form-item label="渠道单价" prop="unitprice">
                    <el-input
                        v-model="form.unitprice"
                        placeholder="请输入单价"
                        maxlength="10"
                        show-word-limit
                        clearable
                        class="formInput"
                    ></el-input>
                </el-form-item>
                <el-form-item label="渠道详情" prop="details">
                    <el-button type="primary" icon="el-icon-plus" @click="formAddDetail">新增项目</el-button>
                    <el-row type="flex" justify="space-between" v-for="(item, index) in form.details" :key="index">
                        <el-col :span="3"> 第{{ index + 1 }}项. </el-col>
                        <el-col :span="7">
                            <el-select v-model="item.nationid" placeholder="国家">
                                <el-option
                                    :label="nitem.name"
                                    :value="nitem.id"
                                    v-for="(nitem, nindex) in NationList"
                                    :key="nindex"
                                ></el-option>
                            </el-select>
                        </el-col>
                        <el-col :span="7">
                            <el-select v-model="item.agentid" placeholder="代理">
                                <el-option
                                    :label="nitem.name"
                                    :value="nitem.id"
                                    v-for="(nitem, nindex) in AgentList"
                                    :key="nindex"
                                ></el-option>
                            </el-select>
                        </el-col>
                        <el-col :span="4">
                            <el-button type="danger" plain icon="el-icon-delete" @click="formDeleteDetail(index)"></el-button>
                        </el-col>
                    </el-row>
                </el-form-item>
            </el-form>

            <span slot="footer" class="dialog-footer">
                <el-button @click="editVisible = false">取 消</el-button>
                <el-button type="primary" @click="saveEdit">确 定</el-button>
            </span>
        </el-dialog>

        <el-dialog title="阶梯价格设置" v-dialogDrag center :visible.sync="priceVisible" width="80%">
            <el-form ref="form" :model="priceform" :rules="priceformRules" label-width="120px">
                <el-form-item label="渠道名称" prop="name">
                    <el-input v-model="priceform.name" maxlength="20" show-word-limit disabled class="formInput"></el-input>
                </el-form-item>
                <el-form-item label="渠道单价" prop="unitprice">
                    <el-input v-model="priceform.unitprice" maxlength="10" show-word-limit disabled class="formInput"></el-input>
                </el-form-item>
                <el-form-item label="阶梯价格表">
                    <div class="FlexRow">
                        <div>
                            <el-button type="primary" icon="el-icon-download" style="margin: 5px 10px 0 0" @click="downloadXlSX"
                                >下载阶梯价格模板</el-button
                            >
                        </div>
                        <channelPriceFileUpload
                            style="margin: 5px 10px"
                            accept="xlsx/*"
                            ref="UploadImage"
                            :limit="1"
                            :id="priceform.id"
                            tip="只能上传xlsx文件"
                            v-on:update:excelData="UpdateExcel"
                        >
                        </channelPriceFileUpload>
                    </div>

                    <el-table :data="PriceTableData" stripe border max-height="300" style="width: 100%">
                        <el-table-column v-for="(item, index) in PriceTableHeader" :key="index" :prop="String(index)" :label="item">
                        </el-table-column>
                    </el-table>
                </el-form-item>
            </el-form>
            <div class="excel">
                <table v-if="priceform.data != null && priceform.data.length > 0">
                    <tr v-for="(item, index) in priceform.data" :key="index">
                        <td v-for="(itemd, indexd) in item" :key="indexd">{{ itemd }}</td>
                    </tr>
                </table>
            </div>

            <span slot="footer" class="dialog-footer">
                <el-button @click="priceVisible = false">取 消</el-button>
            </span>
        </el-dialog>

        <el-dialog title="渠道描述设置" :visible.sync="desVisible" width="100%" fullscreen>
            <el-form ref="desform" :rules="desformRules" label-width="120px">
                <el-form-item label="渠道名称" prop="name">
                    <el-input v-model="desform.name" maxlength="20" show-word-limit disabled class="formInput"></el-input>
                </el-form-item>
                <el-form-item label="渠道时效" prop="name">
                    <el-input v-model="desform.workday" maxlength="50" clearable show-word-limit class="formInput"></el-input>
                </el-form-item>
                <el-form-item label="限制条件" prop="limits">
                    <el-button type="primary" icon="el-icon-plus" @click="formAddLimit">新增项目</el-button>
                    <el-row type="flex" justify="space-between" v-for="(item, index) in desform.limits" :key="index">
                        <el-col :span="3"> 第{{ index + 1 }}项 </el-col>
                        <el-col :span="16">
                            <el-input
                                v-model="item.name"
                                placeholder="请输入条件名称"
                                maxlength="100"
                                show-word-limit
                                clearable
                                class="formInput"
                            ></el-input>
                        </el-col>
                        <el-col :span="16">
                            <el-input
                                v-model="item.value"
                                placeholder="请输入条件描述"
                                maxlength="100"
                                show-word-limit
                                clearable
                                class="formInput"
                            ></el-input>
                        </el-col>
                        <el-col :span="3">
                            <el-button type="danger" plain icon="el-icon-delete" @click="formDeleteLimit(index)"></el-button>
                        </el-col>
                    </el-row>
                </el-form-item>
                <el-form-item label="渠道概述" prop="descriptions">
                    <el-button type="primary" icon="el-icon-plus" @click="formAddDes">新增项目</el-button>
                    <br />
                    <el-row type="flex" justify="space-between" v-for="(item, index) in desform.descriptions" :key="index">
                        <el-col :span="3"> 第{{ index + 1 }}项 </el-col>
                        <el-col :span="16">
                            <el-input
                                v-model="item.description"
                                placeholder="请输入渠道概述"
                                maxlength="100"
                                show-word-limit
                                clearable
                                class="formInput"
                                type="textarea"
                            ></el-input>
                        </el-col>
                        <el-col :span="3">
                            <el-button type="danger" plain icon="el-icon-delete" @click="formDeleteDes(index)"></el-button>
                        </el-col>
                    </el-row>
                </el-form-item>
                <el-form-item label="货物类型" prop="types">
                    <el-checkbox v-for="(item, index) in desform.types" :key="index" v-model="item.ischecked">{{ item.name }}</el-checkbox>
                </el-form-item>
            </el-form>

            <span slot="footer" class="dialog-footer">
                <el-button @click="desVisible = false">取 消</el-button>
                <el-button type="primary" @click="saveDes">确 定</el-button>
            </span>
        </el-dialog>
    </div>
</template>

<script>
import API from '../../../api/index'; //读入restfulAPI
import StringTool from '../../../utils/StringTool';
import JSTool from '../../../utils/JSTool';
import dataTable from './dataTable';

import channelPriceFileUpload from '../../common/upload/channelPriceFileUpload.vue';
export default {
    name: 'courierCannelInTable',
    mixins: [dataTable],
    components: {
        channelPriceFileUpload
    },
    data() {
        let CheckDigit = (rule, value, callback) => {
            if (!StringTool.DigitNumber(String(value))) {
                return callback(new Error('只能为整数和保留两位小数'));
            }
            if (Number(value) < 0) {
                return callback(new Error('只能为正数'));
            }
            callback();
        };
        let CheckFormDetail = (rule, value, callback) => {
            if (value.length <= 0) {
                return callback(new Error('渠道详情至少需要一个项目'));
            }
            for (let i = 0; i < value.length; i++) {
                if (value[i].nationid == null) {
                    return callback(new Error('渠道国家不能为空'));
                }
                if (value[i].agentid == null) {
                    return callback(new Error('渠道代理不能为空'));
                }
            }
            callback();
        };
        return {
            searchSet: {
                name: ''
            },
            query: {
                status: 1,
                index: 1,
                pageSize: 10
            },
            editVisible: false,
            editIsNewAdd: false,

            NationList: [],
            AgentList: [],
            form: {
                name: '',
                unitprice: '',
                details: [{ nationid: null, agentid: null }]
            },
            formRules: {
                name: [
                    { required: true, message: '参数不能为空', trigger: 'change' },
                    { min: 2, max: 20, message: '长度在 2 到 20 个字符', trigger: 'change' }
                ],
                unitprice: [{ validator: CheckDigit, required: true, trigger: 'change' }],
                details: [{ validator: CheckFormDetail, required: true, trigger: 'change' }]
            },
            priceVisible: false,
            priceform: {
                id: '',
                data: []
            },
            priceformRules: {},
            desVisible: false,
            desform: {
                id: '',
                descriptions: [],
                limits: [],
                types: [],
                name: '',
                workday: ''
            },
            desformRules: {}
        };
    },
    created() {
        this.init();
    },

    mounted() {
        // this.PreviewPhotoList = ["http://clips.vorwaerts-gmbh.de/big_buck_bunny.mp4"]
        // this.$refs.PreviewImage.clickHandler()
    },
    computed: {
        PriceTableHeader: function () {
            if (this.priceform && this.priceform.data && this.priceform.data.length > 0) {
                return this.priceform.data[0];
            }
            return [];
        },
        PriceTableData: function () {
            if (this.priceform && this.priceform.data) {
                let list = [];
                this.priceform.data.map((it) => {
                    if (it[0] !== '' && !Number.isNaN(Number(it[0]))) {
                        list.push(it);
                    }
                });
                return list;
            }
            return [];
        }
    },
    methods: {
        downloadXlSX() {
            window.location.href = this.$store.state.baseURL + 'api/Channelpricefile';
        },
        //页面初始化
        init() {
            API.StandardDoWith(API.Nation.Get({ pageSize: 20, status: 1 }), this, {
                success: (detail) => {
                    this.NationList = detail.list;
                }
            });
            API.StandardDoWith(API.Agent.Get({ pageSize: 20, status: 1 }), this, {
                success: (detail) => {
                    this.AgentList = detail;
                }
            });
            this.getData();
        },

        getData() {
            this.tableLoading = true;
            API.StandardDoWith(API.CourierChannel.Get(this.getQuery()), this, {
                success: (detail) => {
                    this.tableData = detail;
                },
                complete: () => {
                    this.tableLoading = false;
                }
            });
        },

        handleAddNew() {
            this.editVisible = true;
            this.editIsNewAdd = true;
            this.form = {
                name: '',
                unitprice: '',
                details: [{ nationid: null, agentid: null }]
            };
        },
        // 编辑操作
        handleEdit(index, row) {
            this.form = JSTool.DeepClone(row);
            this.editIsNewAdd = false;
            this.editVisible = true;
        },
        handlePrice(index, row) {
            this.priceform.id = row.id;
            this.priceform.name = row.name;
            this.priceform.unitprice = row.unitprice;
            API.StandardDoWith(API.ChannelPrice.Get({ id: this.priceform.id }), this, {
                success: (detail) => {
                    this.priceVisible = true;
                    this.priceform.data = detail;
                }
            });
        },
        handleDes(index, row) {
            let desform = {};
            desform.id = row.id;
            desform.name = row.name;
            desform.descriptions = '';
            desform.limits = '';
            desform.types = '';
            desform.workday = '';
            this.desform = desform;
            API.StandardDoWith(API.ChannelDescription.Get({ id: this.desform.id }), this, {
                success: (detail) => {
                    console.log(detail);
                    this.desform.descriptions = detail.descriptions;
                    this.desform.limits = detail.limits;
                    this.desform.types = detail.types;
                    this.desform.workday = detail.workday;
                    this.desVisible = true;
                }
            });
        },
        UpdateExcel(excelData) {
            this.priceform.data = excelData;
        },
        handleDelete(index, row) {
            // 二次确认删除
            this.$confirm('确定要删除吗？', '提示', {
                type: 'warning'
            })
                .then(() => {
                    API.StandardDoWith(API.CourierChannel.Delete({ id: row.id }), this, {
                        success: (detail) => {
                            this.$message.success(`成功删除渠道`);
                            this.getData();
                        }
                    });
                })
                .catch(() => {});
        },
        saveEdit() {
            this.$refs.form.validate((valid) => {
                if (valid) {
                    this.form.unitprice = Number(this.form.unitprice);
                    let net = this.editIsNewAdd ? API.CourierChannel.Post(this.form) : API.CourierChannel.Put(this.form);
                    API.StandardDoWith(net, this, {
                        success: (detail) => {
                            this.editVisible = false;
                            this.$message.success(`成功提交渠道`);
                            this.getData();
                        }
                    });
                } else {
                    this.$message.error(`表单验证失败，无法提交`);
                    return false;
                }
            });
        },
        saveDes() {
            let postdesForm = JSTool.DeepClone(this.desform);
            console.log(postdesForm);
            this.$confirm('确定提交？', '提示', {
                type: 'warning'
            })
                .then(() => {
                    API.StandardDoWith(API.ChannelDescription.Post(postdesForm), this, {
                        success: (detail) => {
                            this.$message.success(`成功提交`);
                            this.desVisible = false;
                        }
                    });
                })
                .catch(() => {});
        },

        formAddDetail() {
            if (!(this.form.details instanceof Array)) {
                this.form.details = [];
            }
            this.form.details.push({ nationid: null, agentid: null, unitprice: '' });
        },
        formAddDes() {
            if (!(this.desform.descriptions instanceof Array)) {
                this.desform.descriptions = [];
            }

            this.desform.descriptions.push({ description: '', order: this.desform.descriptions.length + 1 });
        },
        formAddLimit() {
            if (!(this.desform.limits instanceof Array)) {
                this.desform.limits = [];
            }

            this.desform.limits.push({ name: '', value: '', order: this.desform.limits.length + 1 });
        },
        formDeleteDetail(index) {
            this.form.details.splice(index, 1);
        },
        formDeleteDes(index) {
            this.desform.descriptions.splice(index, 1);
        },
        formDeleteLimit(index) {
            this.desform.limits.splice(index, 1);
        },
        DetailFormatter(row, column, cellValue, index) {
            if (cellValue == null) return '暂无信息';
            return cellValue.length + '条项目';
        }
    }
};
</script>

<style scoped>
@import '../../../assets/css/dataTable.css';
.excel {
    width: 100%;
}
.excel table {
    margin: 0 auto;
    text-align: center;
    border: 1px solid gray;
}
.excel table tr td {
    margin: 5px 10px;
    padding: 5px;
    border: 1px solid gray;
}
</style>
